package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    TokenService tokenService;
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader("authorization");
        //判断是否为空
        if(StringUtils.isEmpty(token)){
            response.setStatus(401);

            return false;
        }
        //解析token 获取登录人
        Claims claims;
        try {
             claims = tokenService.parseToken(token);
        } catch (Exception e) {
            throw new BaseException("无效会话或登录过期");
        }
        //判断claims是否为空
        if(ObjectUtils.isEmpty(claims)){
            response.setStatus(401);
            return false;
        }
        //将获取的信息存入Threadlocal
        Long userId = claims.get("userId", Long.class);
        UserThreadLocal.set(userId);

        return true;
    }
}
